package com.zenithmind.gateway.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zenithmind.common.result.Result;
import com.zenithmind.common.result.ResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 默认错误响应构建器实现
 * 专门负责构建标准化的错误响应
 * 遵循单一职责原则：只负责错误响应的构建逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DefaultErrorResponseBuilder implements ErrorResponseBuilder {
    
    private final ObjectMapper objectMapper;

    @Override
    public DataBuffer buildErrorResponse(ServerHttpResponse response, HttpStatus status, String message, Throwable ex) {
        try {
            Result<Void> errorResult = Result.fail(status.value(), message, null);
            byte[] errorBytes = objectMapper.writeValueAsBytes(errorResult);
            return response.bufferFactory().wrap(errorBytes);
        } catch (JsonProcessingException e) {
            log.error("构建错误响应失败", e);
            // 如果JSON序列化失败，返回简单的错误信息
            String fallbackError = "{\"code\":" + status.value() + ", \"message\":\"" + message + "\"}";
            return response.bufferFactory().wrap(fallbackError.getBytes(StandardCharsets.UTF_8));
        }
    }

    @Override
    public void setResponseHeaders(ServerHttpResponse response, HttpStatus status) {
        response.setStatusCode(status);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    }
}
